import { ref } from 'vue'
import type { IWorkspace } from 'geoserver-helper/interface'
import { restHelperInstance } from './useGeoHelper'

const workspaceList = ref<IWorkspace.WorkspaceOverview[]>([])
// TODO 这个类型需要版本变更后修改为IWorkspace.WorkspaceInfo
const defaultWorkspace = ref<any>()
// const defaultWorkspace = computed(() => {
//     return workspaceList.value.find(findItem => {
//         return findItem.defaultWorkspace == true
//     })
// })

export default function useWorkspaceModal() {
  /**
   * @description: 获取工作空间列表
   * @param {Boolen} refreshData 是否更新数据（使用实时数据）
   * @return {Promise}
   */
  function getWorkspaceList(refreshData = false) {
    if (refreshData || workspaceList.value.length === 0) {
      return new Promise<IWorkspace.WorkspaceOverview[]>((resove, reject) => {
        restHelperInstance
          .getWorkspaceListApi()
          .then((res) => {
            if (res && res.workspaces) {
              workspaceList.value = res.workspaces.workspace
              resove(workspaceList.value)
            } else {
              reject(false)
            }
          })
          .catch(() => {
            reject(false)
          })
      })
    } else {
      return Promise.resolve(workspaceList.value)
    }
  }
  /**
   * @description: 获取默认工作空间
   * @param {Boolen} refreshData 是否更新数据（使用实时数据）
   * @return {Promise}
   */
  function getDefaultWorkspace(refreshData = false) {
    if (refreshData || workspaceList.value.length === 0) {
      return new Promise<any>((resove, reject) => {
        restHelperInstance
          .getWorkspaceInfoApi('default')
          .then((res) => {
            if (res && res.workspace) {
              defaultWorkspace.value = res.workspace
              resove(defaultWorkspace.value)
            } else {
              reject(false)
            }
          })
          .catch(() => {
            reject(false)
          })
      })
    } else {
      return Promise.resolve(defaultWorkspace.value)
    }
  }

  return { workspaceList,defaultWorkspace, getWorkspaceList, getDefaultWorkspace }
}
